// pages/index/index.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: ["https://img1.baidu.com/it/u=2003496092,3295249130&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313", "https://img2.baidu.com/it/u=2220206360,144631063&fm=253&fmt=auto&app=138&f=JPEG?w=752&h=500",
      "https://img1.baidu.com/it/u=2374960005,3369337623&fm=253&fmt=auto&app=120&f=JPEG?w=499&h=312"
    ],
    listData: [],
    current: 'links'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getListData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getListData() {
    db.collection('users').field({
      userPhoto: true,
      nickName: true,
      links: true
    }).orderBy(this.data.current, 'desc').get().then(res => {
      this.setData({
        listData: res.data
      })
    })
  },
  handleLinks(ev) {
    //尚未做限制 每个用户限一次
    let id = ev.target.dataset.id
    wx.cloud.callFunction({
      name: "update",
      data: {
        collection: "users",
        doc: id,
        data: "{links:_.inc(1)}"
      }
    }).then(res => {
      let updated = res.result.stats.updated
      if (updated) {
        let cloneListData = [...this.data.listData]
        for (let i = 0; i < cloneListData.length; i++) {
          if (cloneListData[i]._id == id) {
            cloneListData[i].links++
          }
        }
        this.setData({
          listData: cloneListData
        })
      }
    })
  },
  handleCurrent(ev) {
    let current = ev.target.dataset.current
    if (current == this.data.current) {
      return false
    }
    this.setData({
      current
    }, () => {
      this.getListData()
    })
  },
  handleDetail(ev) {
    let id = ev.target.dataset.id
    wx.navigateTo({
      url: '/pages/detail/detail?userId=' + id,
    })
  }
})